
<template>
  <div class="wrapper">
    <!-- 搜索栏 -->
    <div class="title">
      <p style="font-size: 1.2em; line-height: 100%; margin: 0; text-align: center;">房卡一览</p>
      <br>
      <el-form :inline="true" :model="searchName" class="form" style="margin: -14px 0px 0px 0px;">
        <el-form-item label="房卡名称">
          <el-input v-model="searchName.name" placeholder="请输入房卡名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 折叠面板 -->
    <el-collapse v-model:activeNames="activeNames" accordion class="eco">
      <!-- 循环生成折叠项（每个地图对应一个折叠项） -->
      <el-collapse-item
        v-for="(mapName, index) in mapList"
        :key="index"
        :name="mapName"
      >
        <!-- 折叠项标题 -->
        <template #title>
          <span>{{ mapName }} ({{ roomCardMap[mapName]?.length || 0 }}条数据)</span>
        </template>

        <!-- 折叠内容：表格 -->
        <el-table
          :data="roomCardMap[mapName] || []"
          style="width: 100%; margin-top: 10px;"
        >
          <el-table-column fixed prop="cardImage" label="房卡图片" width="100">
            <template #default="scope">
              <img :src="scope.row.cardImage" width="50" v-if="scope.row.cardImage" />
              <span v-else>无图片</span>
            </template>
          </el-table-column>

          <el-table-column prop="mapName" label="所属地图" width="85" />
          <el-table-column prop="roomName" label="钥匙卡名称" width="120" />
          <el-table-column prop="usageLocation" label="使用地点" width="120" />
          <el-table-column prop="keyCardValue" label="价格" width="90" />
          <el-table-column prop="singleDoorOpenCost" label="单次使用价格" width="120" />

          <el-table-column prop="roomContainers" label="房间包含物资" width="auto">
            <template #default="scope">
              <el-table :data="scope.row.roomContainers" style="width: 100%;">
                <el-table-column prop="containerImage" label="物资图片" width="80">
                  <template #default="contScope">
                    <img :src="contScope.row.containerImage" width="30" v-if="contScope.row.containerImage" />
                    <span v-else>无图片</span>
                  </template>
                </el-table-column>
                <el-table-column prop="containerInfo" label="物资信息" width="auto" />
              </el-table>
            </template>
          </el-table-column>


              <el-table-column label="操作" width="150"> 
                <template #default="scope">
                <el-button type="primary" size="small" @click="update(scope.row.id)">编辑</el-button>
                <el-button type="danger" size="small" @click="delById(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>
  </div>




<el-dialog v-model="dialogFormVisible" :title="formTitle">
  <el-form :model="roomCardForm" :rules="rules" ref="roomCardFormRef">
    <!-- 第一行 -->
    <el-row>
      <el-col :span="12">
        <el-form-item label="所在地图" :label-width="labelWidth" prop="mapName">
          <el-input v-model="roomCardForm.mapName" placeholder="请输入所在地图" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="房名" :label-width="labelWidth" prop="roomName">
          <el-input v-model="roomCardForm.roomName" placeholder="请输入房名" />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 第二行 -->
    <el-row>
      <el-col :span="12">
        <el-form-item label="使用地点" :label-width="labelWidth" prop="usageLocation">
          <el-input v-model="roomCardForm.usageLocation" placeholder="请输入使用地点" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="价格" :label-width="labelWidth" prop="keyCardValue">
          <el-input v-model.number="roomCardForm.keyCardValue" placeholder="请输入价格" />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 第三行：房间内包含的物资（对象数组） -->
    <el-row>
      <el-col :span="24">
        <el-form-item label="房间内包含的物资" :label-width="150" prop="roomContainers">
          <!-- 动态渲染每个物资容器 -->
          <div 
            v-for="(container, index) in roomCardForm.roomContainers" 
            :key="index"
            class="container-group"
          >
            <!-- 物资图片
            <el-col :span="6">
              <el-form-item 
                :prop="'roomContainers.' + index + '.containerImage'" 
                :rules="{ required: true, message: '请填写物资图片' }"
              >
                <el-input 
                  v-model="container.containerImage" 
                  placeholder="物资图片 URL"
                />
              </el-form-item>
            </el-col> -->

            <!-- 物资信息 -->
            <el-col :span="18">
              <el-form-item 
                :prop="'roomContainers.' + index + '.containerInfo'" 
                :rules="{ required: true, message: '请填写物资信息' }"
              >
                <el-input 
                  v-model="container.containerInfo" 
                  placeholder="请填写物资信息（如：大武器箱 x1）"
                />
              </el-form-item>
            </el-col>

          
          </div>

        
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 卡图片上传 -->
    <el-row>
      <el-col :span="12">
        <el-form-item label="卡图片" :label-width="labelWidth">
          <el-upload
            class="avatar-uploader"
            action="/api/upload/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
                :headers="uploadHeaders"
          >
            <img v-if="roomCardForm.cardImage" :src="roomCardForm.cardImage" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="save">确定</el-button>
    </span>
  </template>
</el-dialog>
      <!-- 第七行 内部数组，本模块不用
      <el-row :gutter="5" v-for="expr in emp.exprList">
        <el-col :span="10">
          <el-form-item label="时间" size="small" :label-width="labelWidth">
            <el-date-picker type="daterange" v-model="expr.exprDate" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD"/>
          </el-form-item>
        </el-col>    
        <el-col :span="6">
          <el-form-item label="公司" size="small">
            <el-input placeholder="公司名称" v-model="expr.company"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="职位" size="small">
            <el-input placeholder="职位名称" v-model="expr.job"/>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item size="small">
            <el-button type="danger" @click="delWorkItem(expr)">- 删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
-->

</template>

<script setup lang="ts">
import { onMounted, ref ,computed} from "vue";
import type { RoomCardModel, RoomCardModelResult,RoomContainersModel } from "@/api/model/model";
import { queryRoomCardPageApi,queryRoomCardByIdApi,updateApi,addApi,deleteApi,batchDeleteApi} from "@/api/roomCard";
import { Plus } from '@element-plus/icons-vue'; // 按需导入图标
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadProps } from 'element-plus';
import { useLoginEmpStore } from '@/stores/loginEmp';
const loginEmpStore = useLoginEmpStore();
// 从 store 中获取 token 并计算请求头
const uploadHeaders = computed(() => {
  const loginEmp = loginEmpStore.getLoginEmp();
  return loginEmp && loginEmp.token
    ? { 'token': loginEmp.token }
    : {};
});


const dialogFormVisible = ref(false); // 初始隐藏对话框
const labelWidth = ref<number>(100)
const formTitle = ref<string>("");


 const roomCardForm = ref<RoomCardModel>({
  cardImage: "",
  mapName: '',
  roomName: '',
  usageLocation: '',
  keyCardValue: 0,
  singleDoorOpenCost: 0,
  roomContainers: []
})
const roomContainersForm = ref<RoomContainersModel>({
   roomName:'',
   containerImage:'',
   containerInfo:''
})
//定义表单校验规则
const roomCardFormRef = ref<FormInstance>()
const rules = ref<FormRules<RoomCardModel>>({
  roomName: [
    { required: true, message: '房间为必填项', trigger: 'blur' },
    { min: 2, max: 20, message: '房间名长度为2-20个字', trigger: 'blur' }
  ],
  mapName: [
    { required: false, message: '所在地图', trigger: 'blur' },
    {  min: 0, max: 10, message: '地图', trigger: 'blur' }
  ],
  usageLocation: [
    { required: false, message: '使用地点', trigger: 'blur' }
  ],
  keyCardValue: [
    { required: true, message: '价值', trigger: 'blur' },
    {  min: 0, max: 10, message: '', trigger: 'blur' }
  ],
  singleDoorOpenCost: [
    { required: false, message: '单次使用消耗', trigger: 'blur' },
    {  min: 0, max: 10, message: '', trigger: 'blur' }
  ],
     roomContainers: [
    {
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          return callback(new Error('房间容器不能为空'));
        }
        
        // 遍历每个容器，检查 containerInfo
        for (let i = 0; i < value.length; i++) {
          const container = value[i];
          if (!container.containerInfo || container.containerInfo.trim() === '') {
            return callback(new Error(`第 ${i+1} 个容器的物资信息不能为空`));
          }
          
          // 其他校验规则...
          if (container.containerInfo.length > 50) {
            return callback(new Error(`第 ${i+1} 个容器的物资信息长度不能超过50个字`));
          }
        }
        
        callback(); // 校验通过
      },
      trigger: 'blur'
    }
  ]
})
//重置校验规则
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const addRoomCard = () => {
  console.log("addRoomCard");
  dialogFormVisible.value = true
  resetForm(roomCardFormRef.value) //重置校验规则
  formTitle.value = '新增防具'

  //初始化 表单数据
  roomCardForm.value = {
    cardImage: "",
    mapName: '',
    roomName: '',
    usageLocation: '',
    keyCardValue: 0,
    singleDoorOpenCost: 0,
    roomContainers: [{} as RoomContainersModel]
  }
  
}


// --------------------------------> 修改防具
//1. 查询回显
const update = async (id: number) => {
  dialogFormVisible.value = true
  formTitle.value = '修改员工'
  resetForm(roomCardFormRef.value) //重置校验规则

  //发送请求, 根据ID查询员工信息
  const result = await queryRoomCardByIdApi(id)
  if(result.code) {
    roomCardForm.value = result.data

    //做一步处理 - expr.exprDate
    // const exprList = emp.value.exprList
    // if(exprList && exprList.length>0){
    //   exprList.forEach(expr => {
    //     expr.exprDate = [expr.begin,expr.end]
    //   })
    // }
  }
}

// ----> 新增  / 修改
const save = async (form:FormInstance | undefined) => {
  //校验表单, 如果校验通过, 再提交表单
  if (!form) return
  await form.validate(async (valid, fields) => { //valid 为true, 通过 ; false, 不通过 form.validate is not a function
    if (valid) { //通过

  //     //发送异步请求保存数据
      let result ;
      if(roomCardForm.value.id){ //有id, 执行修改 
        result = await updateApi(roomCardForm.value)
      }else { //没有id,执行新增
        result = await addApi(roomCardForm.value)
      }
      
      if(result.code){//保存成功, 提示成功信息, 关闭对话框, 重新查询
        ElMessage.success('操作成功')
        dialogFormVisible.value = false
        search()
      }else {//保存失败, 提示错误信息
        ElMessage.error(result.msg)
      }
    } else { //不通过
      ElMessage.error('表单校验失败, 不能提交')
    }
  })
}
// ----------------------------------- 删除的逻辑
const delById = (id:number) => {
  ElMessageBox.confirm('您确定要删除该数据吗?', '删除房卡',
    {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'}
  ).then(async () => { //点击确定按钮
    //发送请求, 删除数据
    const result = await deleteApi(id)
    if(result.code){
      ElMessage.success('删除成功')
      search()
    }else {
      ElMessage.error(result.msg)
    }
  })
}

const selectIds = ref<(number| undefined)[]>([]) //封装勾选的id
const handleSelectionChange = (val: RoomCardModel[]) => {
  selectIds.value = val.map(e => e.id) //map方法-遍历数组并对其中的元素进行进一步的处理, 并将结果封装到一个新的数组中
}


const batchDel = () => {
  ElMessageBox.confirm('您确定要删除该数据吗?', '删除防具',
    {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'}
  ).then(async () => { //点击确定按钮
    //发送请求, 删除数据
    const result = await batchDeleteApi(selectIds.value) 
    if(result.code){
      ElMessage.success('删除成功')
      search()
    }else {
      ElMessage.error(result.msg)
    }
  })
}

// 定义地图列表（与后端返回的 key 保持一致）
const mapList = ref<string[]>(["航天基地", "巴克什", "零号大坝", "长弓溪谷"]);

// 定义折叠面板激活状态（默认展开所有项，可改为 [] 折叠所有）
const activeNames = ref<string[]>(mapList.value);

// 使用响应式对象存储所有地图数据（键为地图名称，值为房间列表）
const roomCardMap = ref<RoomCardModelResult>({});

type SearchEmpModel = {
  name: string;
};

const searchName = ref<SearchEmpModel>({ name: "" });

const search = async () => {
  const result = await queryRoomCardPageApi();
  if (result.code === 200) {
    // 直接赋值整个 data 对象（键值对结构）
    roomCardMap.value = result.data;
  }
};
//文件上传
//文件上传成功后触发
const handleAvatarSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
  roomCardForm.value.cardImage = response.data
}

//文件上传前触发
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('文件格式不正确')
    return false //不执行上传操作
  }
  return true
}

onMounted(() => {
  search();
});
</script>

<style scoped>
    body{
        background-color: #bfa;
    }
.el-table {
  font-size: 15px;
}


    .avatar-uploader .avatar {
      width: 78px;
      height: 78px;
      display: block;
    }
    .avatar-uploader .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 78px;
      height: 78px;
      text-align: center;
      border: 1px dashed;
    }

</style>